﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using ET.DBCommon.Model;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;

namespace ET.DBCommon.DAL
{
    public class ExamResultsDAL
    {
        public static ExamResultsModel GetExamResultById(int examresultId)
        {
            ExamResultsModel info = new ExamResultsModel();

            string sql = "SELECT a.*,u.usernumber FROM examresults a inner join userinfo u on a.userid=u.userinfoid where ID = " + examresultId;

            DataSet ds = DbHelper.ExecuteDataset(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                info.ID = Convert.ToInt32(dt.Rows[0][0]);


                if (!(dt.Rows[0][1] is DBNull))
                    info.CreateTime = DateTime.Parse(dt.Rows[0][1].ToString());

                info.UserID = Convert.ToInt32(dt.Rows[0][2].ToString());
                info.Describe = dt.Rows[0][3].ToString();
                if (!(dt.Rows[0][4] is DBNull))
                    info.TotalScore = decimal.Parse(dt.Rows[0][4].ToString());
                info.UserNumber = dt.Rows[0][7].ToString();
            }

            info.ExamresultsTestQuestions = ExamresultsTestQuestionDAL.GetTestQuestionByExamResultsID(info.ID);

            return info;
        }

        public static List<ExamResultsModel> GetExamResults(DateTime start, DateTime end, string describe = "", string usernumber = "")
        {
            string sql = "select a.*,c.usernumber FROM examresults a inner join userinfo c on a.userid=c.UserInfoID " +
                "where a.createtime between '" + start + "' and '" + end + "' and c.usernumber like '%" + usernumber + "%'" +
                " and a.`Describe` like '%" + describe + "%' and EndTime is not null order by a.ID desc";

            DataSet ds = DbHelper.ExecuteDataset(sql);
            List<ExamResultsModel> lst = new List<ExamResultsModel>();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ExamResultsModel info = new ExamResultsModel();
                    info.ID = Convert.ToInt32(dt.Rows[i][0]);
                    if (!(dt.Rows[i][1] is DBNull))
                        info.CreateTime = DateTime.Parse(dt.Rows[i][1].ToString());
                    info.UserID = Convert.ToInt32(dt.Rows[i][2].ToString());
                    info.Describe = dt.Rows[i][3].ToString();
                    if (!(dt.Rows[i][4] is DBNull))
                        info.TotalScore = decimal.Parse(dt.Rows[i][4].ToString());
                    info.UserNumber = dt.Rows[i][7].ToString();
                    if (!(dt.Rows[i][6] is DBNull))
                        info.TestPaperID = int.Parse(dt.Rows[i][6].ToString());
                    info.ExamresultsTestQuestions = ExamresultsTestQuestionDAL.GetTestQuestionByExamResultsID(info.ID, false);
                    lst.Add(info);
                }
            }
            return lst;
        }

        public static DataSet GetExamResult(int examresultId)
        {
            string sql = "SELECT a.*,b.`Describe`,u.usernumber FROM examresults a inner join testpaper b on a.testpaperid=b.testpaperid inner join userinfo u on a.userid=u.userinfoid where ExamResultsID = " + examresultId;

            DataSet ds = DbHelper.ExecuteDataset(sql);
            if (ds != null && ds.Tables.Count > 0)
            {
                ds.Tables[0].TableName = "Table";
                DataSet dsQuestion = ExamresultsTestQuestionDAL.GetTestQuestion(examresultId);
                if (dsQuestion != null && dsQuestion.Tables.Count > 0)
                {
                    DataTable dtQuestion = null;
                    for (int i = 0; i < dsQuestion.Tables[0].Rows.Count; i++)
                    {
                        dtQuestion = dsQuestion.Tables[0].Clone();
                        dtQuestion.Rows.Add(dsQuestion.Tables[0].Rows[i].ItemArray);
                        dtQuestion.TableName = "TableQuestion" + (i + 1);
                        ds.Tables.Add(dtQuestion);
                    }
                    DataSet dsTask = ExamresultsTestQuestionTaskDAL.GetQuestionTask(examresultId);
                    if (dsTask != null && dsTask.Tables.Count > 0)
                    {
                        DataTable dtTask = null;
                        for (int i = 0; i < dsQuestion.Tables[0].Rows.Count; i++)
                        {
                            dtTask = dsTask.Tables[0].Clone();
                            var rows = dsTask.Tables[0].Select(" ExamResultsTestQuestionID=" + dsQuestion.Tables[0].Rows[i]["ExamResultsTestQuestionID"].ToString() + " and isother=0");
                            foreach (DataRow row in dsTask.Tables[0].Rows)
                            {
                                dtTask.ImportRow(row);
                            }
                            dtTask.TableName = "TableTaskNormal" + (i + 1);
                            ds.Tables.Add(dtTask);


                            dtTask = dsTask.Tables[0].Clone();
                            rows = dsTask.Tables[0].Select(" ExamResultsTestQuestionID=" + dsQuestion.Tables[0].Rows[i]["ExamResultsTestQuestionID"].ToString() + " and isother=1");
                            foreach (var row in rows)
                            {
                                dtTask.ImportRow(row);
                            }
                            dtTask.TableName = "TableTaskOther" + (i + 1);
                            ds.Tables.Add(dtTask);
                        }
                    }
                }
            }

            return ds;
        }

        public static bool UpdateExamResults(ExamResultsModel examResultsModel)
        {
            string sql = "update examresults set CreateTime=@CreateTime,ScreenRecordingAddress=@ScreenRecordingAddress WHERE ExamResultsID = @ID";

            MySqlParameter[] parms = {
                new MySqlParameter("@CreateTime", examResultsModel.CreateTime),
                //new MySqlParameter("@ScreenRecordingAddress", examResultsModel.ScreenRecordingAddress),
                new MySqlParameter("@ID", examResultsModel.ID)
            };

            return DbHelper.ExecuteNonQuery(sql, parms) > 0;
        }

        private static Random random = new Random();

        public static int InsertExamResults(ExamResultsModel examResultsModel)
        {
            bool result = false;
            int newId = 0;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead, Timeout = new TimeSpan(0, 0, 60) }))
            {
                string sql = "INSERT INTO `exam` (`CreateTime`, `Describe`, `PaperId`) (SELECT now(),`Describe`, `PaperId` FROM `paper` where paper.Id=@Id)";
                MySqlParameter[] parms = {
                    new MySqlParameter("@Id", examResultsModel.ID)
                };

                if (DbHelper.ExecuteNonQuery(out newId, sql, parms) > 0)
                {
                    //sql = "SELECT concat(case when a.AssistantQuestions is null then '' else a.AssistantQuestions END, ',', a.TestQuestionID) as TestQuestionID " +
                    //    "FROM testquestion a INNER JOIN testpaperquestion b ON a.TestQuestionID = b.TestQuestionID WHERE TestPaperID = " + testPaper.TestPaperID + " ORDER BY b.TestPaperQuestionID";
                    //DataSet ds = DbHelper.ExecuteDataset(sql);
                    //if (ds != null && ds.Tables.Count > 0)
                    //{
                    //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    //    {
                    //        string[] ids = ds.Tables[0].Rows[i]["TestQuestionID"].ToString().TrimStart(',').Split(',');
                    //        string newAssistantQuestions = "";
                    //        for (int j = 0; j < ids.Length; j++)
                    //        {
                    //            sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                    //             "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'" + (j == ids.Length - 1 ? newAssistantQuestions.TrimStart(',') : "") + "',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = " + ids[j] + ")";
                    //            if (DbHelper.ExecuteNonQuery(out int newExamResultsID, sql) > 0)
                    //            {
                    //                if (j != ids.Length - 1) newAssistantQuestions += "," + newExamResultsID;
                    //            }
                    //        }
                    //    }
                    //}
                    if (examResultsModel.ID > 0)
                    {
                        foreach (var question in examResultsModel.ExamresultsTestQuestions)
                        {
                            sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                                         "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = (select TestQuestionID from examresultstestquestion where ID=" + question.AssistantQuestions + "))";
                            if (DbHelper.ExecuteNonQuery(out int newExamResultsID, sql) > 0)
                            {
                                sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                                 "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'" + newExamResultsID + "',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = " + question.TestQuestionID + ")";
                                DbHelper.ExecuteNonQuery(sql);
                            }
                        }
                    }
                    else
                    {
                        sql = "SELECT (case when a.AssistantQuestions is null then '' else a.AssistantQuestions END) as AssistantQuestions, a.TestQuestionID FROM testquestion a INNER JOIN" +
                            " testpaperquestion b ON a.TestQuestionID = b.TestQuestionID WHERE TestPaperID = " + examResultsModel.TestPaperID + " ORDER BY b.TestPaperQuestionID";
                        DataSet ds = DbHelper.ExecuteDataset(sql);
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                string AssistantQuestions = ds.Tables[0].Rows[i]["AssistantQuestions"].ToString();
                                int newExamResultsID = 0;
                                if (!string.IsNullOrWhiteSpace(AssistantQuestions))
                                {
                                    string[] ids = ds.Tables[0].Rows[i]["AssistantQuestions"].ToString().TrimStart(',').Split(',');
                                    int index = random.Next(0, ids.Length - 1);
                                    sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                                     "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = " + ids[index] + ")";
                                    DbHelper.ExecuteNonQuery(out newExamResultsID, sql);
                                }
                                sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                                 "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'" + newExamResultsID + "',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = " + ds.Tables[0].Rows[i]["TestQuestionID"].ToString() + ")";
                                DbHelper.ExecuteNonQuery(sql);
                            }
                        }
                    }
                    sql = "INSERT INTO `examresultstestquestiontask` (`ExamresultsTestQuestionID`,`Order`,`UIOrder`,`Tooltips`,`Prerequisite`,`ResponseTime`,`TimeOut`,`TotalScore`,`TestQuestionTaskID`,IsMain,AfterTaskInterval,AfterTask,MutexTask,`Branch`)" +
                        "(SELECT c.ID,`Order`,`UIOrder`,`Tooltips`,`Prerequisite`,`ResponseTime`,`TimeOut`,`TotalScore`,b.TestQuestionTaskID,b.IsMain,b.AfterTaskInterval,b.AfterTask,b.MutexTask,b.Branch FROM testquestion a INNER JOIN testquestiontask b ON a.TestQuestionID = b.TestQuestionID " +
                        " INNER JOIN examresultstestquestion c ON a.TestQuestionID = c.TestQuestionID WHERE c.ExamResultsID = @ExamResultsID ORDER BY c.ID, b.`UIOrder`)";
                    MySqlParameter[] parms1 = {
                        new MySqlParameter("@TestPaperID", examResultsModel.TestPaperID),
                        new MySqlParameter("@ExamResultsID", newId)
                    };
                    if (DbHelper.ExecuteNonQuery(sql, parms1) > 0)
                    {
                        sql = @"SELECT 0 AS ID,
                                    e.ID AS ExamresultsTestQuestionTaskID,
                                    `StepID`,    
                                    `Parameter`,
                                    `Score`,
                                    `SystemType`,
                                    `TaskType`,
                                    `StepDescribe`,
                                    `DevType`,
                                    `DevID`,
                                    `ScoreStandard`,
                                    0 as  `OperationScore`,
                                    0 as  `ResultScore`,
                                    0 as  `TimeScore`,
                                    0 as  `TotalScore`,
                                    0 as  `CompositeScore`,
                                    `StepContent`,
                                    d.Prerequisite,
                                    `Keyword`,
                                    d.`order`,
                                    `IsRepeat`,
                                    `TestQuestionTaskStepID`,
                                    d.IsCommand,
                                    d.`OutRangeScore`,
                                    d.MutexStep,
                                    d.LimitedDuration,
                                    d.Duration,
                                    d.Deduction,
                                    d.IsKeyStep,
                                    `StepID1`,
                                    `StepDescribe1`,
                                    `DevType1`,
                                    `DevID1`,
                                    `Parameter1`,
                                    `Estimate`
                                FROM
                                    testquestion a
                                        INNER JOIN
                                    testquestiontask b ON a.TestQuestionID = b.TestQuestionID
                                        INNER JOIN
                                    examresultstestquestion c ON a.TestQuestionID = c.TestQuestionID
                                        INNER JOIN
                                    examresultstestquestiontask e ON e.TestQuestionTaskID = b.TestQuestionTaskID and c.ID = e.ExamresultsTestQuestionID
                                        INNER JOIN
                                    testquestiontaskstep d ON d.TestQuestionTaskID = b.TestQuestionTaskID
                                WHERE
                                    c.ExamResultsID = " + newId + " ORDER BY c.ID , b.`Order`,d.`Order`";

                        DataSet ds = DbHelper.ExecuteDataset(sql);
                        var list = new List<ExamresultsTestQuestionTaskStepModel>();

                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var info = ExamresultsTestQuestionTaskStepDAL.GetExamresultsTestQuestionTaskStepModel(dt.Rows[i]);
                            if (!string.IsNullOrWhiteSpace(info.Prerequisite) && info.Prerequisite.Contains(';'))
                            {
                                string[] prerequisites = info.Prerequisite.Split(';');
                                var dic = JsonConvert.DeserializeObject<Dictionary<int, string>>(info.Prerequisite.Split(';')[1]);
                                var newDic = new Dictionary<int, string>();
                                foreach (var keyValue in dic)
                                {
                                    var beforeInfo = list.Find(p => p.TestQuestionTaskStepID == keyValue.Key);
                                    newDic.Add(beforeInfo != null ? beforeInfo.ID : keyValue.Key, keyValue.Value);
                                }
                                info.Prerequisite = prerequisites[0] + ";" + JsonConvert.SerializeObject(newDic) + ";" + prerequisites[2];
                                result = ExamresultsTestQuestionTaskStepDAL.InsertStep(out int newStepId, info);
                                if (result)
                                {
                                    info.ID = newStepId;
                                    list.Add(info);
                                }
                            }
                        }

                        foreach (var info in list.FindAll(p => !string.IsNullOrWhiteSpace(p.MutexStep)))
                        {
                            var mutexs = list.FindAll(p => info.MutexStep.Split(',').Contains(p.TestQuestionTaskStepID.ToString()));
                            info.MutexStep = string.Join(",", mutexs.Select(p => p.ID));
                            result = ExamresultsTestQuestionTaskStepDAL.UpdateMutexStep(info);
                        }
                    }
                }
                scope.Complete();
            }
            return result ? newId : -1;
        }
        public static int InsertExamResultss(ExamResultsModel examResultsModel)
        {
            //北京科研修改逻辑 判断是否存在副场景，存在则examresuls表多添加一条，使表ID对上 modfiy by ljz 2023.7.4
            bool result = false;
            int newId = 0;
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead, Timeout = new TimeSpan(0, 0, 60) }))
            {
                //String sql = "SELECT (case when a.AssistantQuestions is null then '' else a.AssistantQuestions END) as AssistantQuestions, a.TestQuestionID FROM testquestion a INNER JOIN" +
                //            " testpaperquestion b ON a.TestQuestionID = b.TestQuestionID WHERE TestPaperID = " + examResultsModel.TestPaperID + " ORDER BY b.TestPaperQuestionID";
                //DataSet ds1 = DbHelper.ExecuteDataset(sql);
                //if (ds1 != null && ds1.Tables.Count > 0)
                //{
                //    for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                //    {
                //        string AssistantQuestions = ds1.Tables[0].Rows[i]["AssistantQuestions"].ToString();
                //        if (!string.IsNullOrWhiteSpace(AssistantQuestions))
                //        {
                //            sql = "INSERT INTO `examresults` (`CreateTime`,`UserID`, `Describe`, `TestPaperID`) (SELECT now(),"+ examResultsModel .UserID+ ",`Describe`, `TestPaperID` FROM `testpaper` where TestPaperID=" + examResultsModel.TestPaperID + ")";
                //            DbHelper.ExecuteNonQuery(sql);
                //        }
                //    }

                //}

                string sql = "INSERT INTO `examresults` (`CreateTime`,`UserID`, `Describe`, `TestPaperID`) (SELECT now(),@UserID,`Describe`, `TestPaperID` FROM `testpaper` where TestPaperID=@TestPaperID)";
                MySqlParameter[] parms = {
                    new MySqlParameter("@TestPaperID", examResultsModel.TestPaperID),
                    new MySqlParameter("@UserID", examResultsModel.UserID)
                };

                if (DbHelper.ExecuteNonQuery(out newId, sql, parms) > 0)
                {

                    //sql = "SELECT concat(case when a.AssistantQuestions is null then '' else a.AssistantQuestions END, ',', a.TestQuestionID) as TestQuestionID " +
                    //    "FROM testquestion a INNER JOIN testpaperquestion b ON a.TestQuestionID = b.TestQuestionID WHERE TestPaperID = " + testPaper.TestPaperID + " ORDER BY b.TestPaperQuestionID";
                    //DataSet ds = DbHelper.ExecuteDataset(sql);
                    //if (ds != null && ds.Tables.Count > 0)
                    //{
                    //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    //    {
                    //        string[] ids = ds.Tables[0].Rows[i]["TestQuestionID"].ToString().TrimStart(',').Split(',');
                    //        string newAssistantQuestions = "";
                    //        for (int j = 0; j < ids.Length; j++)
                    //        {
                    //            sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                    //             "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'" + (j == ids.Length - 1 ? newAssistantQuestions.TrimStart(',') : "") + "',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = " + ids[j] + ")";
                    //            if (DbHelper.ExecuteNonQuery(out int newExamResultsID, sql) > 0)
                    //            {
                    //                if (j != ids.Length - 1) newAssistantQuestions += "," + newExamResultsID;
                    //            }
                    //        }
                    //    }
                    //}
                    if (examResultsModel.ID > 0)
                    {
                        foreach (var question in examResultsModel.ExamresultsTestQuestions)
                        {
                            //23行调竞赛修改分数统计
                            sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore,TestPaperTotal) " +
                                         "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'',MinusPoints,StationID,StopLaterScore,SubmitElementScore,TestPaperTotal FROM `testquestion` a where a.TestQuestionID = (select TestQuestionID from examresultstestquestion where ID=" + question.AssistantQuestions + "))";
                            if (DbHelper.ExecuteNonQuery(out int newExamResultsID, sql) > 0)
                            {
                                sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                                 "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'" + newExamResultsID + "',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = " + question.TestQuestionID + ")";
                                DbHelper.ExecuteNonQuery(sql);
                            }
                        }
                    }
                    else
                    {
                        sql = "SELECT (case when a.AssistantQuestions is null then '' else a.AssistantQuestions END) as AssistantQuestions, a.TestQuestionID FROM testquestion a INNER JOIN" +
                            " testpaperquestion b ON a.TestQuestionID = b.TestQuestionID WHERE TestPaperID = " + examResultsModel.TestPaperID + " ORDER BY b.TestPaperQuestionID";
                        DataSet ds = DbHelper.ExecuteDataset(sql);
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                string AssistantQuestions = ds.Tables[0].Rows[i]["AssistantQuestions"].ToString();
                                int newExamResultsID = 0;
                                if (!string.IsNullOrWhiteSpace(AssistantQuestions))
                                {
                                    string[] ids = ds.Tables[0].Rows[i]["AssistantQuestions"].ToString().TrimStart(',').Split(',');
                                    //北京科研修改，应小于最大值去掉原ids.length-1
                                    int index = random.Next(0, ids.Length);
                                    sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore) " +
                                     "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'',MinusPoints,StationID,StopLaterScore,SubmitElementScore FROM `testquestion` a where a.TestQuestionID = " + ids[index] + ")";
                                    DbHelper.ExecuteNonQuery(out newExamResultsID, sql);
                                }
                                sql = "INSERT INTO `examresultstestquestion` (`CreateTime`,`ExamResultsID`,`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,AssistantQuestions,MinusPoints,StationID,StopLaterScore,SubmitElementScore,WaitCountDown) " +
                                 "(SELECT now(), " + newId + ",`Name`,`CountDown`,`Describe`,`SceneFile`,`TestQuestionID`,IsMain,'" + newExamResultsID + "',MinusPoints,StationID,StopLaterScore,SubmitElementScore,WaitCountDown FROM `testquestion` a where a.TestQuestionID = " + ds.Tables[0].Rows[i]["TestQuestionID"].ToString() + ")";
                                DbHelper.ExecuteNonQuery(sql);
                            }
                        }
                    }
                        sql = "INSERT INTO `examresultstestquestiontask` (`ExamresultsTestQuestionID`,`Order`,`UIOrder`,`Tooltips`,`Prerequisite`,`ResponseTime`,`TimeOut`,`TotalScore`,`TestQuestionTaskID`,IsMain,AfterTaskInterval,AfterTask,MutexTask,`Branch`)" +
                        "(SELECT c.ID,`Order`,`UIOrder`,`Tooltips`,`Prerequisite`,`ResponseTime`,`TimeOut`,`TotalScore`,b.TestQuestionTaskID,b.IsMain,b.AfterTaskInterval,b.AfterTask,b.MutexTask,b.Branch FROM testquestion a INNER JOIN testquestiontask b ON a.TestQuestionID = b.TestQuestionID " +
                        " INNER JOIN examresultstestquestion c ON a.TestQuestionID = c.TestQuestionID WHERE c.ExamResultsID = @ExamResultsID ORDER BY c.ID, b.`UIOrder`)";
                    MySqlParameter[] parms1 = {
                        new MySqlParameter("@TestPaperID", examResultsModel.TestPaperID),
                        new MySqlParameter("@ExamResultsID", newId)
                    };
                    if (DbHelper.ExecuteNonQuery(sql, parms1) > 0)
                    {
                        sql = @"SELECT 0 AS ID,
                                    e.ID AS ExamresultsTestQuestionTaskID,
                                    `StepID`,    
                                    `Parameter`,
                                    `Score`,
                                    `SystemType`,
                                    `TaskType`,
                                    `StepDescribe`,
                                    `DevType`,
                                    `DevID`,
                                    `ScoreStandard`,
                                    0 as  `OperationScore`,
                                    0 as  `ResultScore`,
                                    0 as  `TimeScore`,
                                    0 as  `TotalScore`,
                                    0 as  `CompositeScore`,
                                    `StepContent`,
                                    d.Prerequisite,
                                    `Keyword`,
                                    d.`order`,
                                    `IsRepeat`,
                                    `TestQuestionTaskStepID`,
                                    d.IsCommand,
                                    d.`OutRangeScore`,
                                    d.MutexStep,
                                    d.LimitedDuration,
                                    d.Duration,
                                    d.Deduction,
                                    d.IsKeyStep,
                                    `StepID1`,
                                    `StepDescribe1`,
                                    `DevType1`,
                                    `DevID1`,
                                    `Parameter1`,
                                    `Estimate`
                                FROM
                                    testquestion a
                                        INNER JOIN
                                    testquestiontask b ON a.TestQuestionID = b.TestQuestionID
                                        INNER JOIN
                                    examresultstestquestion c ON a.TestQuestionID = c.TestQuestionID
                                        INNER JOIN
                                    examresultstestquestiontask e ON e.TestQuestionTaskID = b.TestQuestionTaskID and c.ID = e.ExamresultsTestQuestionID
                                        INNER JOIN
                                    testquestiontaskstep d ON d.TestQuestionTaskID = b.TestQuestionTaskID
                                WHERE
                                    c.ExamResultsID = " + newId + " ORDER BY c.ID , b.`Order`,d.`Order`";

                        DataSet ds = DbHelper.ExecuteDataset(sql);
                        var list = new List<ExamresultsTestQuestionTaskStepModel>();

                        DataTable dt = ds.Tables[0];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var info = ExamresultsTestQuestionTaskStepDAL.GetExamresultsTestQuestionTaskStepModel(dt.Rows[i]);
                            if (!string.IsNullOrWhiteSpace(info.Prerequisite) && info.Prerequisite.Contains(';'))
                            {
                                result = ExamresultsTestQuestionTaskStepDAL.InsertStep(out int newStepId, info);
                                if (result)
                                {
                                    info.ID = newStepId;
                                    list.Add(info);
                                }
                            }
                        }
                        foreach(var info in list)
                        {
                            string[] prerequisites = info.Prerequisite.Split(';');
                            var dic = JsonConvert.DeserializeObject<Dictionary<int, string>>(info.Prerequisite.Split(';')[1]);
                            var newDic = new Dictionary<int, string>();
                            foreach (var keyValue in dic)
                            {
                                var beforeInfo = list.Find(p => p.TestQuestionTaskStepID == keyValue.Key);
                                newDic.Add(beforeInfo != null ? beforeInfo.ID : keyValue.Key, keyValue.Value);
                            }
                            info.Prerequisite = prerequisites[0] + ";" + JsonConvert.SerializeObject(newDic) + ";" + prerequisites[2];
                            ExamresultsTestQuestionTaskStepDAL.UpdatePrerequisite(info.ID, info.Prerequisite);
                        }

                        foreach (var info in list.FindAll(p => !string.IsNullOrWhiteSpace(p.MutexStep)))
                        {
                            var mutexs = list.FindAll(p => info.MutexStep.Split(',').Contains(p.TestQuestionTaskStepID.ToString()));
                            info.MutexStep = string.Join(",", mutexs.Select(p => p.ID));
                            result = ExamresultsTestQuestionTaskStepDAL.UpdateMutexStep(info);
                        }
                    }
                }
                scope.Complete();
            }
            return result ? newId : -1;
        }

        public static void UpdateExamResultsScore(ExamResultsModel currentExamResult)
        {
                string sql = "update examresults set " +
                "TotalScore=" + currentExamResult.TotalScore +
                ",EndTime= '" + currentExamResult.EndTime +
                "',TotalScoreDescribe='" + currentExamResult.TotalScoreDescribe + "'" +
                ",TotalScoreDescribe1='" + currentExamResult.TotalScoreDescribe1 + "'" +
                "WHERE ID =" + currentExamResult.ID;

                DbHelper.ExecuteDataset(sql);

            
        }
        public static void UpdateExamResultsScore1(ExamResultsModel currentExamResult)
        {
            string sql = "update examresults set "
            + "PreTotalScoreDescribe='" + currentExamResult.PreTotalScoreDescribe +
            "',TotalScore=" + currentExamResult.TotalScore +
            ",EndTime= '" + currentExamResult.EndTime +
            "',TotalScoreDescribe='" + currentExamResult.TotalScoreDescribe + "'" +
            ",TotalScoreDescribe1='" + currentExamResult.TotalScoreDescribe1 + "'" +
            "WHERE ID =" + currentExamResult.ID;

            DbHelper.ExecuteDataset(sql);


        }
        public static void UpdateExamResultsTime(String time,int id)
        {
           
                string sql = "update examresults set " + "TestTime='" + time +
                   "' WHERE ID =" + id;
                DbHelper.ExecuteDataset(sql);
            ExamresultsTestQuestionModel.TestTime = false;
        }


        public static String SeclectAlltime(int id)
        {
            string sql = "Select PreTime from examresults WHERE ID =" + id;
            DataSet ds = DbHelper.ExecuteDataset(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                var time = dt.Rows[0][0];
                return time.ToString();

            }
            else
            {
                return "0";
            }
         }
        
        public static String SeclectTotalDescribe(int id)
        {
            string sql = "Select TotalScoreDescribe1 from examresults WHERE ID =" + id;
            DataSet ds = DbHelper.ExecuteDataset(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                var time = dt.Rows[0][0];
                return time.ToString();

            }
            else
            {
                return "0";
            }
        }
        public static String SelectPre(int id)
        {
            string sql = "Select PreTotalScoreDescribe from examresults WHERE ID =" + id;
            DataSet ds = DbHelper.ExecuteDataset(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                var Pre = dt.Rows[0][0];
                return Pre.ToString();

            }
            else
            {
                return "0";
            }
        }
        public static String SeclectAlltime1(int id)
        {
            string sql = "Select TestTime from examresults WHERE ID =" + id;
            DataSet ds = DbHelper.ExecuteDataset(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                var time = dt.Rows[0][0];
                return time.ToString();

            }
            else
            {
                return "0";
            }
        }
        public static void UpdateExamResultsTime1(String time, int id)
        {
            string sql = "update examresults set " + "PreTime='" + time +
                  "' WHERE ID =" + id;
            DbHelper.ExecuteDataset(sql);
            ExamresultsTestQuestionModel.PreTime = false;
        }
        

        public static String getLevel(int TestPaperId)
        {
            string sql = "SELECT Level FROM testpaper where TestPaperID=" + TestPaperId;
            DataSet ds = DbHelper.ExecuteDataset(sql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                var Pre = dt.Rows[0][0];
                return Pre.ToString();

            }
            else
            {
                return "0";
            }
        }
        public static List<EventRecordModel> GetEventRecords(int examresultId)
        {
            string sql = "select * from eventrecordmodel where ExamResultsID = " + examresultId;
            DataSet ds = DbHelper.ExecuteDataset(sql);
            List<EventRecordModel> list = new List<EventRecordModel>();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    EventRecordModel info = new EventRecordModel();
                    info.ExamResultsID = Convert.ToInt32(dt.Rows[i]["ExamResultsID"]);
                    info.CreateTime = Convert.ToDateTime(dt.Rows[i]["CreateTime"].ToString());
                    info.Message = dt.Rows[i]["Message"].ToString();
                    info.QuestionID = int.Parse(dt.Rows[i]["QuestionID"].ToString());
                    info.EventLogType = (LogType)Convert.ToInt32(dt.Rows[i]["EventLogType"]);

                    list.Add(info);
                }
            }
            return list;
        }
    }
}
